package com.senjoeson.teamfriends.activity;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Switch;
import android.widget.TextView;

import com.senjoeson.teamfriends.R;
import com.senjoeson.teamfriends.bean.Question;
import com.senjoeson.teamfriends.bean.User;
import com.senjoeson.teamfriends.utils.ALog;
import com.senjoeson.teamfriends.utils.MyToast;
import com.senjoeson.teamfriends.utils.SPUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class SettingActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener, View.OnClickListener {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.addfriend_notice)
    Switch mAddfriendNotice;
    @BindView(R.id.teamfriend_notice)
    Switch mTeamfriendNotice;
    @BindView(R.id.voice_notice)
    Switch mVoiceNotice;
    @BindView(R.id.move_notice)
    Switch mMoveNotice;
    @BindView(R.id.settingquestion)
    Button mSettingQuesion;
    @BindView(R.id.question1)
    TextView mTvQuestionv1;
    @BindView(R.id.anwser1)
    TextView mTvAnwser1;
    @BindView(R.id.question2)
    TextView mTvQuestion2;
    @BindView(R.id.anwser2)
    TextView mTvAnwser2;
    @BindView(R.id.questionmode1)
    LinearLayout mQuesionMode1;
    @BindView(R.id.questionmode2)
    LinearLayout mQuesionMode2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        initCheck();
        User currentUser = BmobUser.getCurrentUser(User.class);
        if (currentUser.isAddfriendflag() ) {  //如果你设置了问题
            mQuesionMode1.setVisibility(View.VISIBLE);
            mQuesionMode2.setVisibility(View.VISIBLE);
            initQuestions(currentUser.getObjectId(), mTvQuestionv1, mTvAnwser1, mTvQuestion2, mTvAnwser2);
        } else {
            mQuesionMode1.setVisibility(View.GONE);
            mQuesionMode2.setVisibility(View.GONE);
        }
        mAddfriendNotice.setOnCheckedChangeListener(this);
        mTeamfriendNotice.setOnCheckedChangeListener(this);
        mVoiceNotice.setOnCheckedChangeListener(this);
        mMoveNotice.setOnCheckedChangeListener(this);
        mSettingQuesion.setOnClickListener(this);
}

    /**
     * 推送设置选项
     */
    private void initCheck() {
        //todo  推送设置选项
        mAddfriendNotice.setChecked(SPUtils.getBoolean("addfriendNotice", false));
        mTeamfriendNotice.setChecked(SPUtils.getBoolean("teamfriendNotice", false));
        mVoiceNotice.setChecked(SPUtils.getBoolean("voiceNotice", false));
        mMoveNotice.setChecked(SPUtils.getBoolean("moveNotice", false));
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {

            case R.id.addfriend_notice:
                SPUtils.putBoolean("addfriendNotice", isChecked);
                break;
            case R.id.teamfriend_notice:
                SPUtils.putBoolean("teamfriendNotice", isChecked);
                break;
            case R.id.voice_notice:
                SPUtils.putBoolean("voiceNotice", isChecked);
                break;
            case R.id.move_notice:
                SPUtils.putBoolean("moveNotice", isChecked);
                break;

        }
        buttonView.setChecked(isChecked);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.settingquestion:
                User currentUser = BmobUser.getCurrentUser(User.class);
                showPopWindow(SettingActivity.this, currentUser);
                break;
        }

    }

    /**
     * 设置页面的透明度
     *
     * @param bgAlpha 1表示不透明
     */
    public static void setBackgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        activity.getWindow().setAttributes(lp);
    }

    /**
     * 显示一个popwindow
     * @param context
     * @param currentUser
     */
    private void showPopWindow(Context context, final User currentUser) {

        final View view = LayoutInflater.from(context).inflate(R.layout.popupwindow_setquestion, null);
        final PopupWindow popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(-00000);
        popupWindow.setBackgroundDrawable(dw);
        setBackgroundAlpha(SettingActivity.this, 1f);
        popupWindow.setAnimationStyle(R.anim.anim);
        final EditText question1 =  view.findViewById(R.id.question1);
        final EditText anwser1 =  view.findViewById(R.id.anwser1);
        final EditText question2 =  view.findViewById(R.id.question2);
        final EditText anwser2 =  view.findViewById(R.id.anwser2);

        if (currentUser.isAddfriendflag()) {
            initQuestions(currentUser.getObjectId(), question1, anwser1, question2, anwser2);
        }
        final Button mSubmit = view.findViewById(R.id.submit);
        mSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String mQuestion1 = question1.getText().toString().trim();
                final String mAnwser1 = anwser1.getText().toString().trim();
                final String mQuestion2 = question2.getText().toString().trim();
                final String mAnwser2 = anwser2.getText().toString().trim();
                boolean allHasContent = judgeContentNotNull(mQuestion1, mQuestion2, mAnwser1, mAnwser2);
                if (!allHasContent) {
                    MyToast.showToast("设置问题和答案不能为空哦！");
                    return;
                }
                BmobQuery<Question> questionBmobQuery = new BmobQuery<>();
                questionBmobQuery.addWhereEqualTo("userid", currentUser.getObjectId());
                questionBmobQuery.findObjects(new FindListener<Question>() {
                    @Override
                    public void done(List<Question> list, BmobException e) {
                        if (list != null && list.size() > 0) {
                            Question question = list.get(0);
                            question.setQuestion1(mQuestion1);
                            question.setQuestion2(mQuestion2);
                            question.setAnswer1(mAnwser1);
                            question.setAnswer2(mAnwser2);
                            question.update(new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null) {
                                        ALog.d("更新成功");
                                    } else {
                                        ALog.d(e.getMessage());
                                    }

                                    popupWindow.dismiss();
                                }
                            });
                        } else {
                            Question question = new Question();
                            question.setUserid(currentUser.getObjectId());
                            question.setQuestion1(mQuestion1);
                            question.setQuestion2(mQuestion2);
                            question.setAnswer1(mAnwser1);
                            question.setAnswer2(mAnwser2);
                            question.save(new SaveListener<String>() {
                                @Override
                                public void done(String s, BmobException e) {
                                    if (e == null) {
                                        currentUser.setAddfriendflag(true);
                                        currentUser.update(new UpdateListener() {
                                            @Override
                                            public void done(BmobException e) {
                                                if (e == null) {
                                                    ALog.d("已更新");
                                                } else {
                                                    ALog.d(e.getMessage());
                                                }
                                            }
                                        });
                                        MyToast.showToast("设置成功");
                                        if (currentUser.isAddfriendflag() ) {
                                            mQuesionMode1.setVisibility(View.VISIBLE);
                                            mQuesionMode2.setVisibility(View.VISIBLE);
                                            initQuestions(currentUser.getObjectId(), mTvQuestionv1, mTvAnwser1, mTvQuestion2, mTvAnwser2);
                                        } else {
                                            mQuesionMode1.setVisibility(View.GONE);
                                            mQuesionMode2.setVisibility(View.GONE);
                                        }
                                    } else {
                                        MyToast.showToast(e.getMessage());
                                    }
                                    popupWindow.dismiss();
                                }
                            });
                        }
                    }
                });
            }
        });

        popupWindow.showAtLocation(findViewById(android.R.id.content).getRootView(), Gravity.CENTER, 0, 0);
    }

    /**
     * 初始化设置问题的数据
     *
     * @param userid    用户id
     * @param question1 问题1
     * @param anwser1   答案1
     * @param question2 问题2
     * @param anwser2   答案2
     */
    private void initQuestions(String userid, final TextView question1, final TextView anwser1, final TextView question2, final TextView anwser2) {
        BmobQuery<Question> questionBmobQuery = new BmobQuery<>();
        questionBmobQuery.addWhereEqualTo("userid", userid);
        questionBmobQuery.findObjects(new FindListener<Question>() {
            @Override
            public void done(List<Question> list, BmobException e) {
                if (list != null && list.size() > 0) {
                    Question question = list.get(0);
                    question1.setText(String.format("%s", question.getQuestion1()));
                    anwser1.setText(String.format("%s", question.getAnswer1()));
                    question2.setText(String.format("%s", question.getQuestion2()));
                    anwser2.setText(String.format("%s", question.getAnswer2()));
                } else {
                    ALog.d("没有设置问题");
                }

            }
        });
    }

    /**
     * 判断是否有空值出现
     * @param contents 判断的对象
     * @return 只要有一个为空就为false
     */
    private boolean judgeContentNotNull(String... contents) {
        for (String content : contents) {
            if (TextUtils.isEmpty(content)) {
                return false;
            }
        }
        return true;
    }
}
